package com.lshl.lingshang.http.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ViewModel;


import com.lshl.lingshang.bean.ErrorBean;
import com.lshl.lingshang.http.manager.ApiManager;
import com.lshl.lingshang.http.manager.RetrofitManager;
import com.lshl.lingshang.http.requestbean.DialogBean;
import com.lshl.lingshang.ui.bean.TitleBean;
import com.lshl.lingshang.utils.LogUtil;
import com.lshl.lingshang.utils.NetworkUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 项目名:    TODO-MVVM
 * 包名       com.azhon.basic.lifecycle
 * 文件名:    BaseViewModel
 * 创建时间:  2019-03-27 on 10:44
 * 描述:     TODO ViewModel基类，管理rxJava发出的请求，ViewModel销毁同时也取消请求
 *
 * @author 阿钟
 */

public abstract class BaseViewModel extends ViewModel implements LifecycleObserver {

    /**
     * 管理RxJava请求
     */
    private CompositeDisposable compositeDisposable;
    /**
     * 用来通知 Activity／Fragment 是否显示等待Dialog
     */
    protected DialogLiveData<DialogBean> showDialog = new DialogLiveData<>();
    /**
     * 当ViewModel层出现错误需要通知到Activity／Fragment
     */
    protected MutableLiveData<Object> error = new MutableLiveData<>();

    public TitleLiveData<TitleBean> title = new TitleLiveData<>();

    protected ErrorLiveData<ErrorBean> errorMsg = new ErrorLiveData<>();


    public ApiManager manager = RetrofitManager.getInstance().createApiManager();


    /**
     * 添加 rxJava 发出的请求
     */
    protected void addDisposable(Disposable disposable) {
        if (compositeDisposable == null || compositeDisposable.isDisposed()) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    public void getShowDialog(LifecycleOwner owner, Observer<DialogBean> observer) {
        LogUtil.showAll("=====getShowDialog===");
        showDialog.observe(owner, observer);
    }

    public void getShowTitle(LifecycleOwner owner, Observer<TitleBean> observer) {
        title.observe(owner, observer);
    }

    public void getError(LifecycleOwner owner, Observer<Object> observer) {
        error.observe(owner, observer);
    }

    public void getErrorMsg(LifecycleOwner owner, Observer<ErrorBean> observer) {
        errorMsg.observe(owner, observer);
    }

    /**
     * ViewModel销毁同时也取消请求
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
        showDialog = null;
        error = null;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void onCreate() {
        setTitle();
    }

    public abstract void setTitle();

    /**
     * 线程调度
     */
    public <T> ObservableTransformer<T, T> compose() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        // 可添加网络连接判断等
//                                if (!NetworkUtils.isNetworkAvailable(BaseActivity.this)) {
//                                    Toast.makeText(BaseActivity.this, R.string.toast_network_error, Toast.LENGTH_SHORT).show();
//                                }
                    }
                })
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }
}
